package com.thinvent.remotepassword.util;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class ThreadPoolUtils {

    // 私有构造方法，防止实例化  
    private ThreadPoolUtils() {}

    // 创建固定大小的线程池  
    public static ExecutorService newFixedThreadPool(int corePoolSize) {
        return Executors.newFixedThreadPool(corePoolSize);
    }

    // 创建单线程的线程池  
    public static ExecutorService newSingleThreadExecutor() {
        return Executors.newSingleThreadExecutor();
    }

    // 创建定时线程池  
    public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize) {
        return Executors.newScheduledThreadPool(corePoolSize);
    }

    // 关闭线程池  
    public static void shutdownExecutorService(ExecutorService executorService) {
        if (executorService != null && !executorService.isShutdown()) {
            executorService.shutdown();
            try {
                // 等待一段时间让线程池中的任务完成  
                if (!executorService.awaitTermination(60, TimeUnit.SECONDS)) {
                    // 如果超时，则强制关闭  
                    executorService.shutdownNow();
                }
            } catch (InterruptedException e) {
                // 如果在等待期间被中断，则重新中断当前线程  
                Thread.currentThread().interrupt();
                // 强制关闭线程池  
                executorService.shutdownNow();
            }
        }
    }

    // 关闭定时线程池  
    public static void shutdownScheduledExecutorService(ScheduledExecutorService scheduledExecutorService) {
        shutdownExecutorService((ExecutorService) scheduledExecutorService);
    }
}